package com.xayy.core.antlr4.utils;

import cn.kawins.base.result.CheckResult;
import cn.kawins.base.utils.CollUtil;
import com.xayy.core.antlr4.exception.TelemetryNullException;
import com.xayy.core.antlr4.model.TelemetryVo;
import com.xayy.core.constant.ConfigCalPath;
import com.xayy.mgt.service.AssociationParameterService;
import com.xayy.mgt.service.NodeInfoService;
import com.xayy.mgt.service.impl.OutInterfaceServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取遥测数据的方法
 *
 * @author Nie
 * @version V1.0
 * @date 2023/8/11 11:19
 */
@Component
@Slf4j
public class TelemetryUtil {
    private static TelemetryUtil telemetryUtil;

    @Autowired
    private AssociationParameterService accService;
    @Autowired
    private NodeInfoService nodeInfoService;

    @Autowired
    private ConfigCalPath configCalPath;

    @PostConstruct
    public void init() {
        telemetryUtil = this;
        telemetryUtil.accService = this.accService;
        telemetryUtil.nodeInfoService = this.nodeInfoService;
        telemetryUtil.configCalPath = this.configCalPath;
    }

    /**
     * 获取关联参数配置中的遥测数据
     *
     * @param telemetryVo 入参
     * @return 遥测值
     */
    public static List<Double> selectTelemetry(TelemetryVo telemetryVo) {
        if (Boolean.FALSE.equals(telemetryVo.getCheckSyntax())) {
            return getList(telemetryVo);
        }
        return CollUtil.newArrayList(10D, 15D, 20D);
    }

    private static List<Double> getList(TelemetryVo telemetryVo) {
        // todo 预留调用遥测接口
        List<Double> values = new ArrayList<>();
        String paramCode = telemetryVo.getParamCode();
        String[] split = paramCode.split(":");
        if (split.length != 2)
            return values;
        telemetryVo.setParamCode(split[1]);
        CheckResult<List<com.xayy.mgt.model.vo.TelemetryVo>> telemetry = telemetryUtil.nodeInfoService.getTelemetry(telemetryVo);
        if (telemetry.no())
            return values;
        List<com.xayy.mgt.model.vo.TelemetryVo> data = telemetry.getData();
        if (CollUtil.isEmpty(data)) {
            log.error("没有获取到参数：" + telemetryVo.getParamCode() + "得遥测数据");
            throw new TelemetryNullException("没有获取到参数：" + telemetryVo.getParamCode() + "得遥测数据");
        }
        for (com.xayy.mgt.model.vo.TelemetryVo datum : data) {
            Double value = datum.getValue();
            values.add(value);
        }
        OutInterfaceServiceImpl.addLogs("获取遥测参数："+telemetryUtil.configCalPath.getTelAndFaultUrl()+"/health-xw-back-moni/v1.0/imitate/getTelemetryData 数据："+telemetryVo);
        OutInterfaceServiceImpl.addLogs("获取遥测参数数量："+values.size());
        return values;
    }

}
